package com.itheima.springbootwebtlias.aspect;

import com.itheima.springbootwebtlias.mapper.OperateLogMapper;
import com.itheima.springbootwebtlias.pojo.OperateLog;
import com.itheima.springbootwebtlias.util.CurrentHolder;
import jakarta.servlet.http.HttpServletRequest;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired
    private HttpServletRequest request;

    // 环绕通知  切入点表达式  execution + annotation
    @Around("execution(* com.itheima.springbootwebtlias.service.*Service.*(..)) && @annotation(com.itheima.springbootwebtlias.anno.LogOperation)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        // 执行方法
        Object result = pjp.proceed();
        // 当前时间
        long endTime = System.currentTimeMillis();
        // 耗时
        long costTime = endTime - startTime;

       /*//从请求头中获取当前登录的员工令牌，解析令牌，获取当前登录用户的ID
        String token = request.getHeader("token"); //  获取令牌
        Claims claims = JwtUtils.parseJWT(token); // 解析令牌
        Integer id = (Integer) claims.get("id"); //  获取当前登录用户的ID*/


        // 构建日志对象
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(pjp.getTarget().getClass().getName());
        operateLog.setMethodName(pjp.getSignature().getName());
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));
        operateLog.setReturnValue(result + "");
        operateLog.setCostTime(costTime);
//两种方式获取用户Id，这种方式更加灵活
        operateLog.setOperateEmpId(CurrentHolder.getCurrentId());

        // 插入日志
        operateLogMapper.insert(operateLog);
        return result;
    }
}
